package com.ttloner1.preparedstatement;

import com.ttloner1.bean.ExamStudent;
import com.ttloner1.util.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;

/**
 * @author TTLoner
 * @date 2021/6/22 9:51
 * @description
 * 使用preparestatement创建一个通用的针对不同表的查询方法
 */
public class Query {
    public <T> ArrayList<T> getInstance(Class<T> clazz, String sql, String[] args) throws InstantiationException {
        ArrayList<T> result = new ArrayList<>();
        //连接数据库
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            //预编译
            ps = conn.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            //获取结果
            rs = ps.executeQuery();
            //获取元数据
            ResultSetMetaData metaData = rs.getMetaData();
            int count = metaData.getColumnCount();
            while(rs.next()){
//                ExamStudent ES = new ExamStudent();
                T t = clazz.newInstance();
                for(int i=0;i<count;i++){
                    //获取列的列名，不推荐使用
//                    String CName = metaData.getColumnName(i+1);
                    String CName = metaData.getColumnLabel(i+1);
                    //获取列的别名：getColumnLabel
                    //通过反射获取
                    Field field = clazz.getDeclaredField(CName);
                    field.setAccessible(true);
                    field.set(t, rs.getObject(i+1));
                }
                result.add(t);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }finally {
            //关闭流
            JDBCUtils.closeConnection(conn,ps,rs);
        }
        return result;
    }

    @Test
    public void test() throws InstantiationException {
        String sql="select * from examstudent";
        String[] args={};
        ArrayList<ExamStudent> rs = getInstance(ExamStudent.class, sql, args);
        rs.forEach(System.out::println);
//        for(ExamStudent RS:rs){
//            System.out.println(RS);
//        }
    }
}
